<?php


namespace app\api\v1\controller;


use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use iflow\annotation\lib\value\Data;
use iflow\Response;
use iflow\router\Controller;
use iflow\router\lib\request\GetMapping;
use iflow\router\lib\request\PostMapping;

#[Data]
#[Controller('%v1%')]
class GraphQLController
{

    /**
     * GraphQL 执行入口
     * @param string $query
     * @param string $schema
     * @param string $operationName
     * @param string $variables
     * @return Response|array
     */
    #[PostMapping('exec/<?:schema>')]
    #[GetMapping('exec/<?:schema>')]
    public function exec(string $query, string $schema = 'shortChain', string $operationName = '', string $variables = ''): Response|array
    {
        $queryType = config('graphql@'.$schema);

        if (!$queryType) {
            return [
                'errors' => 'GraphQLSchema does not exists'
            ];
        }

        try {
            $schema = new Schema([
                'query' => $queryType -> buildQueryFieldsObject()
            ]);

            $result = GraphQL::executeQuery($schema, $query, variableValues: $variables ?: null, operationName: $operationName ?: null);
            return $result -> toArray();
        } catch (\Throwable $exception) {
            return [
                'errors' => $exception -> getMessage()
            ];
        }
    }

}